/* eslint-disable @typescript-eslint/no-explicit-any */

// 定义枚举表示不同的按钮类型
export enum ButtonType {
  FORM_SUBMIT = 'FORM_SUBMIT',
  SEND_MESSAGE = 'SEND_MESSAGE',
  LIKE_COLLECT = 'LIKE_COLLECT',
  SEARCH = 'SEARCH',
  LINK = 'LINK',
}

export enum EventType {
  TOGGLE = 'TOGGLE',
}

// 约定常见场景的时间（单位：毫秒）
const THROTTLE_TIME: { [key in ButtonType | EventType]: number } = {
  [ButtonType.FORM_SUBMIT]: 2000,
  [ButtonType.SEND_MESSAGE]: 1000,
  [ButtonType.LIKE_COLLECT]: 500,
  [ButtonType.SEARCH]: 1000,
  [ButtonType.LINK]: 5000,
  [EventType.TOGGLE]: 100,
}
// 示例使用
function getThrottleTime(buttonType: ButtonType | EventType = ButtonType.FORM_SUBMIT): number {
  return THROTTLE_TIME[buttonType]
}

// app-plus 中没有assert测试
// console.assert(getThrottleTime(ButtonType.FORM_SUBMIT) === 2000, 'FORM_SUBMIT按钮的节流时间为2000毫秒') // 输出 2000

/**
 * 导出一个名为throttle的函数，该函数接受两个参数：func和wait
 * @param func 函数
 * @param wait 时间
 * @returns func
 */
export const throttle = (func: (...args: any[]) => any, wait: ButtonType | EventType = ButtonType.FORM_SUBMIT) => {
  const time = getThrottleTime(wait)
  let inThrottle: boolean
  return function (...args: any[]) {
    if (!inThrottle) {
      func.call(null, ...args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), time)
    }
  }
}
